package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.crawl.domain.airfreight.AbstractPlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.CabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnCabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnDoublePlaneInfoEntity;
import com.foreveross.crawl.exception.FlightInfoNotFoundException;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.google.common.collect.Maps;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class KunmingAdapter extends AbstractAdapter {
    public KunmingAdapter(TaskModel taskQueue) {
        super(taskQueue);
        // TODO Auto-generated constructor stub
    }

    HttpClient client = null;


    @Override
    public List<Object> paraseToVo(Object fetchObject) throws Exception {
        if (fetchObject == null) {
            throw new FlightInfoNotFoundException("无该航班");
        }
        List list = (List) fetchObject;
        if (list.size() == 0) {
            throw new FlightInfoNotFoundException("无该航班");
        }
        return list;
    }

    @Override
    public String getUrl() throws Exception {
        return null;
    }

    private String getPageHtml() throws Exception {
        HttpRequestBase request = null;
        String html = null;
        for (int i = 0; i < 3; i++) {
            try {
                String flightType = this.taskQueue.getIsReturn() == 1 ? "WF" : "DC";
                String flightDates = this.taskQueue.getIsReturn() == 1 ? (taskQueue.getFlightDate() + ";" + taskQueue.getReturnGrabDate()) : taskQueue.getFlightDate();
                StringBuffer url = new StringBuffer("http://www.airkunming.com/booking/flightSearch?");
                url.append("dstCity=").append(taskQueue.getToCity());
                url.append("&orgCity=").append(taskQueue.getFromCity());
                url.append("&flightDates=").append(flightDates);
                url.append("&flightType=").append(flightType);
                url.append("&source=").append("airkunming");

                request = new HttpPost(url.toString());

                html = super.excuteRequest(getHttpClient(), request, true);
                rollbackProxyIp(true);
                break;
            } catch (Exception e) {
                logger.error("数据获取错误：" + e.getMessage());
                rollbackProxyIp(false);
                switchProxyipByHttClient();
            }
        }

        if (html == null) {
            throw new Exception("抓取页面数据失败");
        }

        super.appendPageContents(html);
        super.setLenghtCount(super.getSourceWebPageContents().length());
        return html;
    }

    @Override
    public Object fetch(String url) throws Exception {
        List<AbstractPlaneInfoEntity> result = new ArrayList<AbstractPlaneInfoEntity>();
        String html = getPageHtml(); // 获取数据 ;


        // 14/07/03 加上税费
        String jcjsfRegex = "机场建设费.*?</label>(.*?)</label>";
        String ryfjsRegex = "燃油附加税.*?</label>(.*?)</label>";
        List<String> jcjsList = null;
        List<String> ryfjList = null;
        try {
            jcjsList = RegHtmlUtil.retrieveLinks(html, jcjsfRegex, 1);
            ryfjList = RegHtmlUtil.retrieveLinks(html, ryfjsRegex, 1);
        } catch (Exception e) {
            logger.info("抓取税费失败");
            throw e;
        }
        Double taxesPrice = Double.valueOf(jcjsList.get(0)) + Double.valueOf(ryfjList.get(0));

        buildPlaneInfos(false, result, html, taskQueue.getFromCity(), taskQueue.getToCity(), taxesPrice);

        if (taskQueue.getIsReturn() != 1) {
            PlaneInfoEntityBuilder.buildLimitPrice(result);
            return result;
        }
        List returnResult = new ArrayList<AbstractPlaneInfoEntity>();

        taxesPrice = Double.valueOf(jcjsList.get(1)) + Double.valueOf(ryfjList.get(1));
        buildPlaneInfos(true, returnResult, html, taskQueue.getToCity(), taskQueue.getFromCity(), taxesPrice);
        for (AbstractPlaneInfoEntity from : result) {
            PlaneInfoEntityBuilder.getDoubleEntity(from).getReturnPlaneInfos().addAll(returnResult);
        }
        PlaneInfoEntityBuilder.buildRelation(result, returnResult);
        PlaneInfoEntityBuilder.buildLimitPrice(result);

        return result;
    }

    private void buildPlaneInfos(boolean isReturn, Collection<AbstractPlaneInfoEntity> result, String html, String from, String to, Double taxesPrice) throws Exception {
        Document doc = Jsoup.parse(html);
        Elements lines = doc.select("div[name^=segment]");

        for (Element line : lines) {
            Elements tds = line.select("div>table>tbody>tr>td");
            String flightNo = tds.get(0).select("div").get(0).text();
            String flightType = tds.get(0).select("div").get(1).text();
            String startTime = tds.get(1).select("div").get(0).text();
            String fromCity = tds.get(1).select("div").get(1).text();
            String endTime = tds.get(3).select("div").get(0).text();
            String toCity = tds.get(3).select("div").get(1).text();


            AbstractPlaneInfoEntity planeInfo = null;
            if (isReturn) {
                planeInfo = PlaneInfoEntityBuilder.buildPlaneInfo(this.taskQueue, "KY", "昆航", "昆明航空", startTime, endTime, flightNo, null, null, null, flightType, ReturnDoublePlaneInfoEntity.class);
            } else {
                planeInfo = PlaneInfoEntityBuilder.buildPlaneInfo(this.taskQueue, "KY", "昆航", "昆明航空", startTime, endTime, flightNo, null, null, null, flightType);
            }
            planeInfo.setFromCityName(fromCity);
            planeInfo.setToCityName(toCity);

            //舱位
            Elements cabins = tds.get(5).select(".zi");
            Map cabinMap = Maps.newHashMap();

            for (Element cabin : cabins) {
                String cabinName = cabin.select("td").get(0).text();
                String price = cabin.select("td").get(2).text();
                price = price.replaceAll("￥", "");
                this.buildCabin(isReturn, cabinMap, planeInfo, null, null, cabinName, PlaneInfoEntityBuilder.getDouble(price), taxesPrice);
            }

            if (isReturn) {
                PlaneInfoEntityBuilder.getReturnDoubleEntity(planeInfo).getReturnCabins().addAll(cabinMap.values());
            } else {
                if (taskQueue.getIsReturn() != 1) {
                    PlaneInfoEntityBuilder.getSingleEntity(planeInfo).getCabins().addAll(cabinMap.values());
                } else {
                    PlaneInfoEntityBuilder.getDoubleEntity(planeInfo).getCabins().addAll(cabinMap.values());
                }
            }

            if (cabins.size() > 0)
                result.add(planeInfo);
        }
    }

    public void buildCabin(boolean isReturn, Map cabinMap, AbstractPlaneInfoEntity planeInfo, String cabinType, String subCabinName, String productName, Double price, Double taxesPrice) {
        if (isReturn) {
            ReturnCabinEntity cabinEntity = new ReturnCabinEntity();
            cabinEntity.setCabinType(cabinType);
            cabinEntity.setPlaneInfoEntity(planeInfo);
            cabinEntity.setPrice(price);
            cabinEntity.setProductName(productName);
            cabinEntity.setSubCabinName(subCabinName);
            cabinEntity.setTaxesPrice(taxesPrice);
            cabinEntity.setOriginalPrice(price + taxesPrice);
            cabinMap.put(price, cabinEntity);
        } else {
            CabinEntity cabinEntity = new CabinEntity();
            cabinEntity.setCabinType(cabinType);
            cabinEntity.setPlaneInfoEntity(planeInfo);
            cabinEntity.setPrice(price);
            cabinEntity.setProductName(productName);
            cabinEntity.setSubCabinName(subCabinName);
            cabinEntity.setTaxesPrice(taxesPrice);
            cabinEntity.setOriginalPrice(price + taxesPrice);
            cabinMap.put(price, cabinEntity);
        }
    }

    @Override
    public boolean validateFetch(Object fetchObject) throws Exception {
        // TODO Auto-generated method stub
        return true;
    }

    public String getRegex1(String from, String to) {
        String regex = "class=\"tablex9 yuding_hb\" name=\"segment" + from + to + "\".+?<li class=\"liax10\"><div.+?>(.+?)</div>.+?";// 航班号
        regex += "<li class=\"liax10\">.*?<div.*?>.*?<label>.+?<label>(.+?)</label>.+?<label>.+?<label>(.+?)</label>.+?";// 开始时间 到达时间
        regex += "<li.+?<label>.+?<label>(.+?)</label>.+?<label>.+?<label>(.+?)</label>";// 飞机型号，中转站
        regex += "(.+?)onclick=\"showMoreClasses.+?</li>.+?</li>(.+?)</div>\\s*?</div>\\s*?</div>\\s*?</div>\\s*?</div>";
        return regex;
    }

    public String getRegex2() {
        String regex = "<li class=\"liax10\".+?</li>";
        return regex;
    }

    public String getRegex6() {
        String regex = "value=\"(.+?);(.+?)\\*.+?\"";
        return regex;
    }

    public String getRegex5() {
        String regex = "moreClassesDiv";
        return regex;
    }

    public String getRegex3() {
        String regex = "<div class=\"tablex9 yuding_hb\" name=\"segment.*?\">(.+?</li>)\\s*?</div>";
        return regex;
    }

    public String getRegex4() {
        String regex = "<li class=\"liax9\".+?<div.*?>(.+?)</div></li>";
        return regex;
    }

    public String getRegex7() {
        String regex = "<li class=\"liax10\"[^\r]+?><div[^\r]+?>([^\\s]+?)<br>\\(([^\r]+?)\\)</div></li><li[^\r]+?><div[^\r]+?<input[^\r]+?>([^\r]+?)</div>";
        return regex;
    }
}
